package com.ruoyi.web.controller.edh;

import com.egzosn.pay.common.bean.PayMessage;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.pay.wachatpay.WxPayConFig;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.wxpay.WXPayUtil;
import com.ruoyi.edh.domain.bo.OrderPayBo;
import com.ruoyi.edh.domain.params.WxpayParam;
import com.ruoyi.edh.service.IEdhMasterOrderAliPayService;
import com.ruoyi.edh.service.IEdhMasterOrderWxPayService;
import com.ruoyi.edh.service.IEdhOrderService;
import com.ruoyi.edh.config.WxPayConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/edh/wx")
@Api(tags = "微信支付")
public class EdhWxPayOrderController extends WxPayConFig {

    @Autowired
    private IEdhMasterOrderWxPayService iEdhMasterOrderWxPayService;

    @Autowired
    private IEdhMasterOrderAliPayService iEdhMasterOrderAliPayService;

    @Autowired
    private IEdhOrderService edhOrderService;

    @Autowired
    private WxPayConfig wxPayConfig;

    /**
     * wx获取支付预订单信息
     *
     * @return 支付预订单信息
     */
    @RequestMapping("/order")
    @ApiOperation("主订单wxApp支付接口")
    public Map<String, Object> app(String masterOrderNo) {
        Map<String, Object> data = new HashMap<>(20);
        data.put("code", 200);
        Map<String, String> params = new HashMap<String, String>(16);
        try {
            params = iEdhMasterOrderWxPayService.masterOrderWxPay(masterOrderNo);
        } catch (Exception e) {
            data.put("code", 500);
            e.printStackTrace();
        }
        data.put("orderInfo", params);
        return data;
    }

    /**
     * 支付回调地址 方式一
     * <p>
     * 方式二，{@link #(HttpServletRequest)} 是属于简化方式， 试用与简单的业务场景
     *
     * @param request 请求
     * @return 是否成功
     * @throws IOException IOException
     * @see #(HttpServletRequest)
     */
    @Deprecated
    @PostMapping(value = "/wxPayOrder")
    public String payBackBefore(HttpServletRequest request) throws Exception {
        InputStream inStream = ServletUtils.getRequest().getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = WXPayUtil.xmlToMap(resultxml);
        outSteam.close();
        inStream.close();

        Map<String, String> return_data = new HashMap<String, String>();
        if (!WXPayUtil.isSignatureValid(params, wxPayConfig.getKey())) {
            // 支付失败
            return_data.put("return_code", "FAIL");
            return_data.put("return_msg", "return_code不正确");
            return WXPayUtil.mapToXml(return_data);
        } else {
            log.info("===============付款成功==============");
            //创建支付业务对象
            OrderPayBo orderPayBo = new OrderPayBo();
            String outTradeNo = params.get("out_trade_no").toString();
            orderPayBo.setOutTradeNo(outTradeNo);
            orderPayBo.setTradeNo(params.get("trade_no").toString());
            orderPayBo.setSellerId(params.get("seller_id").toString());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            orderPayBo.setTimestamp(sdf.parse(String.valueOf(params.get("gmt_create"))));
            orderPayBo.setPaymentType("0");
            orderPayBo.setOriginalPrice(new BigDecimal(String.valueOf(params.get("total_amount"))));
            Boolean aBoolean = iEdhMasterOrderAliPayService.payMentSuccess(orderPayBo);
            if (!aBoolean) {
                //把付款状态修改为付款失败
                edhOrderService.updateOrderStatusFailure(outTradeNo);
                return service.getPayOutMessage("fail", "订单更新失败").toMessage();
            }
            PayMessage payMessage = new PayMessage();
            payMessage.setPayType("微信");
            payMessage.setMsgType("支付成功");
            return_data.put("return_code", "SUCCESS");
            return_data.put("return_msg", "OK");
            return WXPayUtil.mapToXml(return_data);
        }
    }

    //--------------------- 微信小程序支付 ---------------------

    /**
     * 微信小程序支付
     */
    @PostMapping("/pay")
    @ApiOperation("微信小程序支付")
    public AjaxResult pay(@RequestBody @Validated WxpayParam wxpayParam) {
        AjaxResult ajax = AjaxResult.success();
        //小程序支付
        Map<String, String> params = iEdhMasterOrderWxPayService.miniProgramPay(wxpayParam);
        ajax.put("orderInfo", params);
        return ajax;
    }

//    /**
//     * 微信回调地址
//     */
//    @ApiIgnore
//    @PostMapping("/notifyWeiXinPay")
//    public String notifyWeiXinPay() throws Exception {
//        System.out.println("微信支付回调");
//        InputStream inStream = ServletUtils.getRequest().getInputStream();
//        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
//        byte[] buffer = new byte[1024];
//        int len = 0;
//        while ((len = inStream.read(buffer)) != -1) {
//            outSteam.write(buffer, 0, len);
//        }
//        String resultxml = new String(outSteam.toByteArray(), "utf-8");
//        Map<String, String> params = com.ruoyi.common.utils.wxpay.WXPayUtil.xmlToMap(resultxml);
//        outSteam.close();
//        inStream.close();
//
//        Map<String, String> return_data = new HashMap<String, String>();
//        if (!WXPayUtil.isSignatureValid(params, wxPayConfig.getKey())) {
//            // 支付失败
//            return_data.put("return_code", "FAIL");
//            return_data.put("return_msg", "return_code不正确");
//            return WXPayUtil.mapToXml(return_data);
//        } else {
//            log.info("===============付款成功==============");
//            //创建支付业务对象
//            OrderPayBo orderPayBo = new OrderPayBo();
//            String outTradeNo = params.get("out_trade_no").toString();
//            orderPayBo.setOutTradeNo(outTradeNo);
//            orderPayBo.setTradeNo(params.get("trade_no").toString());
//            orderPayBo.setSellerId(params.get("seller_id").toString());
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            orderPayBo.setTimestamp(sdf.parse(String.valueOf(params.get("gmt_create"))));
//            orderPayBo.setPaymentType("0");
//            orderPayBo.setOriginalPrice(new BigDecimal(String.valueOf(params.get("total_amount"))));
//            Boolean aBoolean = iEdhMasterOrderAliPayService.payMentSuccess(orderPayBo);
//            if (!aBoolean) {
//                //把付款状态修改为付款失败
//                edhOrderService.updateOrderStatusFailure(outTradeNo);
//                return service.getPayOutMessage("fail", "订单更新失败").toMessage();
//            }
//            PayMessage payMessage = new PayMessage();
//            payMessage.setPayType("微信");
//            payMessage.setMsgType("支付成功");
//            return_data.put("return_code", "SUCCESS");
//            return_data.put("return_msg", "OK");
//            return com.ruoyi.common.utils.wxpay.WXPayUtil.mapToXml(return_data);
//        }
//    }

}
